package com.qiwenshare.file.config.es;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    private static final int TIME_OUT = 5 * 60 * 1000;

    @Bean
    public ElasticsearchClient elasticsearchClient(){
        //final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        //credentialsProvider.setCredentials(
            //AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456"));
        RestClient client = RestClient.builder(new HttpHost("cogonline", 9201,"http"))
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    httpClientBuilder.setMaxConnTotal(30);
                    httpClientBuilder.setMaxConnPerRoute(10);
                    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
                    return httpClientBuilder;
                })
                .setRequestConfigCallback(
                        httpClientBuilder -> {
                            httpClientBuilder.setConnectTimeout(5000);
                            httpClientBuilder.setSocketTimeout(TIME_OUT);
                            httpClientBuilder.setConnectionRequestTimeout(TIME_OUT);
                            return httpClientBuilder;
                        }
                ).build();
        ElasticsearchTransport transport = new RestClientTransport(client,new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}